const fs = require("fs");
const path = require("path");
const { WxPay } = require("../../tool/node-wxpay/index");
const config = require("../../config/config.json");
const logsUtil = require("../../tool/logs");
const sysConfigSerivce = require("../service/sys_config");

let { appid, mch_id, partner_key, notify_url, refund_notify_url } = config.wechat;
let wxpay = null;
module.exports = {
  init() {
    if (!wxpay) {
      let pfx = fs.readFileSync(path.join(__dirname, "../../cert/apiclient_cert.p12"));
      wxpay = new WxPay({ appid, mch_id, partner_key, pfx });
    }
  },

  async createUnifiedOrder({ good_desc, openid, order_sn, total_fee, ip, attach, trade_type = "JSAPI" }) {
    try {
      this.init();

      total_fee = total_fee * 100; // 换算金额为元

      // 测试环境支付1分钱
      let wxEnvironment = await sysConfigSerivce.getWxEnvironment();
      if (!wxEnvironment) {
        total_fee = 1;
      }

      attach = encodeURIComponent(attach);

      const params = {
        body: good_desc,
        out_trade_no: order_sn,
        total_fee,
        openid,
        attach,
        spbill_create_ip: ip,
        notify_url, // 微信会发通知到你服务器上的接口路径
        trade_type,
      };

      const result = await wxpay.unifiedorder(params);
      console.log("result==========>", result);
      return result;
    } catch (error) {
      logsUtil.errError(error.message);
      throw new Error(error.message);
    }
  },
  // 查询订单
  async query(out_trade_no) {
    this.init();
    const result = await wxpay.query({ out_trade_no });
    return result;
  },

  // 关闭订单
  async closeOrder(out_trade_no) {
    this.init();
    const reuslt = await wxpay.closeorder({ out_trade_no });
    return reuslt;
  },
  // 申请退款
  async requestRefund(out_trade_no, refund_fee) {
    this.init();
    refund_fee = parseFloat(refund_fee);
    refund_fee = refund_fee * 100; // 换算金额为元
    // 测试环境支付1分钱
    let wxEnvironment = await sysConfigSerivce.getWxEnvironment();
    if (!wxEnvironment) {
      refund_fee = 1;
    }

    let result = await wxpay
      .refund({
        out_trade_no: out_trade_no,
        out_refund_no: out_trade_no,
        total_fee: refund_fee,
        refund_fee: refund_fee,
        notify_url: refund_notify_url,
      })
      .catch((error) => {
        logsUtil.errError(error.message);
        throw new Error(error.message);
      });

    return result;
  },
};
